// amis 环境配置
import axios from 'axios';
import { message } from 'antd';
import { render as renderAmis } from 'amis-core';
import {alert} from 'amis-ui';
import { history } from '@@/core/history';
import { AlertComponent, ToastComponent } from 'amis';
import React from 'react';

import 'amis/lib/helper.css';
import 'amis/sdk/iconfont.css';
import 'amis/lib/themes/cxd.css';


export default function useAmis(schema: any) {
  const [messageApi, contextHolder] = message.useMessage();

  const env = {
    // 下面三个接口必须实现
    fetcher: ({
                url, // 接口地址
                method, // 请求方法 get、post、put、delete
                data, // 请求数据
                responseType,
                config, // 其他配置
                headers // 请求头
              }: any) => {
      let newConfig = config || {};
      let newData = data;
      newConfig.withCredentials = true;
      if (responseType) {
        newConfig.responseType = responseType;
      }

      if (newConfig.cancelExecutor) {
        newConfig.cancelToken = new (axios as any).CancelToken(
          newConfig.cancelExecutor
        );
      }

      newConfig.headers = headers || {};
      newConfig.headers['respFormat'] = 'amis';

      // 设置 token
      const token = localStorage.getItem('token');
      if (token) {
        newConfig.headers['Authorization'] = `Bearer ${token}`;
      }

      if (method === 'get' || method === 'delete') {
        if (newData) {
          newConfig.params = newData;
          newData = null;
        }
      } else if (newData && newData instanceof FormData) {
        newConfig.headers = newConfig.headers || {};
        newConfig.headers['Content-Type'] = 'multipart/form-data';
      } else if (
        newData &&
        typeof newData !== 'string' &&
        !(newData instanceof Blob) &&
        !(newData instanceof ArrayBuffer)
      ) {
        newData = JSON.stringify(newData);
        newConfig.headers = newConfig.headers || {};
        newConfig.headers['Content-Type'] = 'application/json';
      }

      const resp = (axios as any)[method](url, newData, newConfig);

      // 如果登录失效，跳转到登录页
      resp.then(({data}: any) => {
        if (data.status === 1003) {
          const path = history.location.pathname !== '/login';
          history?.push('/login?redirect=' + (path ? history.location.pathname : '/'));
          messageApi.error(data.msg || '请求失败');
        }
      });

      return resp
    },
    isCancel: (value: any) => (axios as any).isCancel(value),
    notify: (
      type: 'info' | 'success' | 'error' | 'warning' | 'loading' /**/,
      msg: string /*提示内容*/
    ) => {
      messageApi.open({
        content: msg,
        type,
      });
    },
    alert,
    // confirm,
  };

  const Dom = renderAmis(
    schema,
    {
      // props...
    },
    env
  );

  return () => (
    <>
      <ToastComponent key="toast" position={'top-right'} />
      <AlertComponent key="alert" />
      {Dom}
      {contextHolder}
    </>
  );
}